package com.example.springboot.controller;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.springboot.annotaion.PassToken;
import com.example.springboot.annotaion.UserLoginToken;
import com.example.springboot.entity.User;
import com.example.springboot.service.UserService;
import com.example.springboot.util.TokenUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 梦之旅
 * @since 2020-11-09
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    // 登录
    @PostMapping("/login")
    @UserLoginToken
    public String login(User user){
        Map<String, Object> map = new HashMap<>();

        QueryWrapper<User> queryWrapper = Wrappers.query();
        queryWrapper.eq("username", user.getUsername());
        User userForBase = userService.getOne(queryWrapper);
        if(userForBase == null){
            map.put("message","登录失败,用户不存在");
            return JSONUtil.toJsonStr(map);
        }else {
            if (!userForBase.getPassword().equals(user.getPassword())){
                map.put("message","登录失败,密码错误");
                return JSONUtil.toJsonStr(map);
            }else {
                String token = TokenUtil.getToken(userForBase);
                map.put("token", token);
                map.put("user", userForBase);
                return JSONUtil.toJsonStr(map);
            }
        }
    }

    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage(){
        return "你已通过验证";
    }

    @PassToken(required = true)
    @GetMapping("/getToken")
    public String getToken(){
        User user = new User();
        user.setUsername("张三");
        user.setPassword("123456");
        return TokenUtil.getToken(user);
    }

    @RequiresPermissions("user:show")
    @RequestMapping("showUser")
    public String showUser(){
        return "这是用户信息";
    }
}
